import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';

// 简单的身份验证配置（从环境变量读取）
const ADMIN_CREDENTIALS = {
  username: process.env.ADMIN_USERNAME || 'admin',
  password: process.env.ADMIN_PASSWORD || 'admin123'
};

// JWT密钥（从环境变量读取）
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-this-in-production';

// 检查用户是否已登录
export function isAuthenticated(): boolean {
  try {
    const cookieStore = cookies();
    const token = cookieStore.get('admin-token');
    
    if (!token) {
      return false;
    }
    
    // 简单的token验证（生产环境应该使用更安全的JWT验证）
    return token.value === 'authenticated';
  } catch (error) {
    return false;
  }
}

// 客户端检查认证状态（支持localStorage备用方案）
export function isAuthenticatedClient(): boolean {
  if (typeof window === 'undefined') return false;
  
  // 首先检查localStorage
  const localToken = localStorage.getItem('admin-token');
  if (localToken === 'authenticated') {
    return true;
  }
  
  // 然后检查cookie
  const cookieValue = document.cookie
    .split('; ')
    .find(row => row.startsWith('admin-token='))
    ?.split('=')[1];
    
  return cookieValue === 'authenticated';
}

// 验证用户凭据
export function verifyCredentials(username: string, password: string): boolean {
  return username === ADMIN_CREDENTIALS.username && password === ADMIN_CREDENTIALS.password;
}

// 创建认证token
export function createAuthToken(): string {
  return 'authenticated';
}

// 中间件函数检查认证状态
export function checkAuth(request: NextRequest) {
  const token = request.cookies.get('admin-token');
  const isLoginPage = request.nextUrl.pathname === '/admin/login';
  const isAdminRoute = request.nextUrl.pathname.startsWith('/admin');
  
  // 如果已经在登录页面，且已认证，重定向到管理后台
  if (isLoginPage && token?.value === 'authenticated') {
    return NextResponse.redirect(new URL('/admin', request.url));
  }
  
  // 如果访问管理后台但未认证，重定向到登录页面
  if (isAdminRoute && !isLoginPage && token?.value !== 'authenticated') {
    return NextResponse.redirect(new URL('/admin/login', request.url));
  }
  
  return NextResponse.next();
}